<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>找工作助手</title>
    <!-- 引入全局配置文件 -->
    <script src="../js/config.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .controls {
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        .message {
            margin-bottom: 10px;
            padding: 5px;
            border-radius: 3px;
        }
        .user {
            background-color: #e3f2fd;
        }
        .assistant {
            background-color: #f3e5f5;
        }
        .system {
            background-color: #e8f5e8;
        }
        .input-area {
            display: flex;
            margin-top: 10px;
        }
        .input-area input {
            flex: 1;
            padding: 5px;
            margin-right: 10px;
        }
        button {
            padding: 5px 10px;
            cursor: pointer;
        }
        .job-item {
            border: 1px solid #ddd;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }
        .personal-info {
            background-color: #f0f8ff;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .loading {
            display: none;
        }
        /* 通知样式 */
        .notification {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
            max-width: 300px;
        }
        .notification button {
            float: right;
            background: none;
            border: none;
            color: white;
            font-weight: bold;
            cursor: pointer;
        }
        /* 倒计时样式 */
        .countdown {
            margin-left: 10px;
            color: #ff6b6b;
            font-weight: bold;
        }
        /* 计数器样式 */
        .counter-control {
            margin-top: 10px;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 5px;
        }
        .counter-control input {
            width: 60px;
            padding: 5px;
            margin: 0 10px;
        }
    </style>
</head>
<body>
    <!-- 在<body>标签内添加 -->
    <audio id="notificationSound" preload="auto">
        <source src="../voice/a.mp3" type="audio/mpeg">
    </audio>
    <!-- 添加返回主页的链接 -->
    <div style="margin-bottom: 20px;">
        <a href="../index.html" style="display: inline-block; padding: 10px 15px; background-color: #6c757d; color: white; text-decoration: none; border-radius: 5px;">← 返回主页</a>
    </div>
    <h1>找工作助手</h1>
    
    <div class="controls">
        <button id="fetchJobBtn">获取并分析工作信息</button>
        <span id="countdown" class="countdown"></span>
        <button id="clearBtn">清空消息</button>
        <span id="loadingIndicator" class="loading">正在获取工作信息...</span>
    </div>
    
    <!-- 添加计数器控制 -->
    <div class="counter-control">
        <label for="runCount">设置运行次数:</label>
        <input type="number" id="runCount" min="1" value="10">
        <button id="startCounterBtn">开始计数运行</button>
        <button id="stopCounterBtn">停止计数运行</button>
        <span id="counterStatus"></span>
    </div>
    
    <div id="jobInfo" style="display: none;">
        <h3>当前工作信息</h3>
        <div id="jobDetails"></div>
    </div>
    
    <div class="messages" id="messages">
        <p>等待消息...</p>
    </div>
    
    <div class="input-area">
        <input type="text" id="messageInput" placeholder="输入您的回复...">
        <button id="sendBtn">发送</button>
    </div>
    
    <h2>工作分析结果</h2>
    <div id="jobs">
        <p>暂无工作分析结果</p>
    </div>

    <script>
let PERSONAL_INFO = "";
let lastFetchTime = 0;
let knownJobIds = new Set();
let countdownInterval = null;
const sound = document.getElementById('notificationSound');
// 使用配置文件中的 BASE_URL
const BASE_URL = APP_CONFIG.BASE_URL;

// 计数器相关变量
let runCounter = 0;
let totalRuns = 0;
let counterInterval = null;
let isCounterRunning = false;

// 通知相关变量
let pendingNotifications = [];

// 显示通知
function showNotification(message) {
    // 检查页面是否可见
    if (document.hidden) {
        // 如果页面不可见，将通知存储起来
        pendingNotifications.push({
            message: message,
            timestamp: Date.now()
        });
        // 页面重新可见时显示通知
        document.addEventListener('visibilitychange', showPendingNotifications, { once: true });
    } else {
        // 页面可见时直接显示通知
        displayNotification(message);
    }
}

// 实际显示通知的函数
function displayNotification(message) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.innerHTML = `
        <strong>新工作提醒</strong><br>
        ${message}
        <button onclick="this.parentElement.remove()">×</button>
    `;
    
    // 添加到页面中
    document.body.appendChild(notification);
    
    // 20秒后自动移除通知（原来是5秒）
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 20000);
}

// 显示待处理通知的函数
function showPendingNotifications() {
    // 当页面重新可见时，显示所有待处理的通知
    while (pendingNotifications.length > 0) {
        const notification = pendingNotifications.shift();
        // 检查通知是否仍然有效（例如，1分钟内的通知才显示）
        if (Date.now() - notification.timestamp < 60000) {
            displayNotification(notification.message);
        }
    }
}

// 更新倒计时显示
function updateCountdown() {
    const currentTime = Date.now();
    const timeRemaining = 3 * 60 * 1000 - (currentTime - lastFetchTime);
    
    if (timeRemaining > 0) {
        const seconds = Math.ceil(timeRemaining / 1000);
        document.getElementById('countdown').textContent = `还有 ${seconds} 秒可以获取`;
        document.getElementById('fetchJobBtn').disabled = true;
    } else {
        document.getElementById('countdown').textContent = '';
        document.getElementById('fetchJobBtn').disabled = false;
    }
}

// 启动倒计时
function startCountdown() {
    // 先立即更新一次
    updateCountdown();
    
    // 清除之前的倒计时（如果有的话）
    if (countdownInterval) {
        clearInterval(countdownInterval);
    }
    
    // 启动新的倒计时
    countdownInterval = setInterval(updateCountdown, 1000);
}

// 获取工作信息
async function fetchJob() {
    // 检查是否在5分钟内已经获取过工作信息
    const currentTime = Date.now();
    if (currentTime - lastFetchTime < 5 * 60 * 1000) {
        const remainingTime = Math.ceil((5 * 60 * 1000 - (currentTime - lastFetchTime)) / 1000);
        addMessage(`请等待 ${remainingTime} 秒后再获取新的工作信息`, 'system');
        return;
    }

    try {
        // 显示加载状态
        document.getElementById('loadingIndicator').style.display = 'inline';
        document.getElementById('fetchJobBtn').disabled = true;
        addMessage('正在获取工作信息...', 'system');
        
        // 调用真实的API获取工作信息
        const response = await fetch('https://www.xmrc.com.cn/api/RecruitPositionSearch?page=1&pageSize=20&rnd=0.7342038148627013', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            },
            body: JSON.stringify({
                "ticket": "1755915449",
                "version": "1.0",
                "platform": 0,
                "sign": "6d033bd68f45e42f78f2eb5395eb90d5",
                "data": {
                    "CreateTime": -1,
                    "CreateTimeName": "不限",
                    "UpdateTime": -1,
                    "UpdateTimeName": "不限",
                    "WelfareName": "不限",
                    "Welfare": "",
                    "Key": "机械设计",
                    "Degree": -1,
                    "DegreeName": "不限",
                    "Age": -1,
                    "AgeName": "不限",
                    "WorkYear":-1,
                    "WorkYearName": "不限",
                    "SalaryType": -1,
                    "SalaryTypeName": "不限",
                    "Salary": -1,
                    "SalaryName": "不限",
                    "CompanyTypeId": -1,
                    "CompanyTypeIdName": "不限",
                    "JobPropertyTypeId": -1,
                    "JobPropertyTypeIdName": "不限",
                    "JobDateId": -1,
                    "JobDateIdName": "不限",
                    "OrderBy": 1,
                    "OrderByName": "发布时间",
                    "AscDesc": 1,
                    "AscDescName": "降序",
                    "SearchType": 0
                }
            })
        });
        
        if (!response.ok) {
            throw new Error(`获取工作信息失败: ${response.status}`);
        }
        
        const result = await response.json();
        
        // 检查返回数据是否有效
        if (!result.Data || !result.Data.Items || result.Data.Items.length === 0) {
            throw new Error('未找到相关工作信息');
        }
        
        let jobData = result.Data.Items[0];
        const filteredJobs = result.Data.Items.filter(job => 
    !job.Address.includes('泉州') && 
         !job.JobName.includes('经理')
     && !job.JobName.includes('主管')&&
      !job.JobName.includes('电工')&&
       
     !job.JobName.includes('应届生')&&
    !job.JobDetail.includes('独立')&& 
    !job.JobDetail.includes('忠诚')&&
    !job.JobDetail.includes('流体')&&
    !job.JobDetail.includes('材料')&&
    !job.JobDetail.includes('稳定')&&
     !job.JobDetail.includes('外向')

    
);

if (filteredJobs.length != 0) {
   jobData = filteredJobs[0];
}


        const jobId = jobData.Id;
       // console.log('获取到的工作信息:', jobData);
        // 检查是否为新ID
        const isNewJob = !knownJobIds.has(jobId);

        window.currentJob = jobData;
        lastFetchTime = currentTime; // 更新最后获取时间
                // 如果是新ID，则添加到已知ID集合中
        if (isNewJob) {
            knownJobIds.add(jobId);
            // 显示右下角提示弹窗
            
           document.getElementById('jobDetails').innerHTML = `
            <p><strong>职位:</strong> ${jobData.JobName || '未知'}</p>
                       <p><strong>学历要求:</strong> ${jobData.NeedEduBackgroundName || '不限'}</p>
             <p><strong>薪资:</strong> ${jobData.RealSalary || '面议'}</p>
            <p><strong>公司:</strong> ${jobData.CompanyName || '未知'}</p>
            <p><strong>工作详情:</strong> ${jobData.JobDetail || '无详情'}</p>
            <p><strong>工作地址:</strong> ${jobData.Address || '未提供'}</p>
            <p><strong>公司性质:</strong> ${jobData.CompanyTypeName|| '无描述'}</p>
 
            <p><strong>工作经验:</strong> ${jobData.NeedWorkLengthName || '不限'}</p>
                        <p><strong>职位类型:</strong> ${jobData.JobTypesName || '未知'}</p>
            <p><strong>公司规模:</strong> ${jobData.CompanySizeName || '无描述'}</p>
            <p><strong>ID:</strong> ${jobData.Id || '未知'}</p>
            <p><strong>状态:</strong> ${isNewJob ? '新工作' : '已查看过'}</p>
        `;
        document.getElementById('jobInfo').style.display = 'block';
        
        addMessage(`获取到工作: ${jobData.JobName || '未知职位'} (${isNewJob ? '新工作' : '已查看过'})`, 'system');
        
        // 自动分析工作
        await analyzeJob();

        }
        
             else {
            addMessage(`已查看过工作: ${jobData.JobName || '未知职位'}`, 'system');
        }
        
        // 保存已知ID列表和最后获取时间
        localStorage.setItem('knownJobIds', JSON.stringify(Array.from(knownJobIds)));
        localStorage.setItem('lastFetchTime', lastFetchTime.toString());
        
        // 启动倒计时
        startCountdown();
    } catch (error) {
        addMessage(`获取工作信息失败: ${error.message}`, 'system');
    } finally {
        document.getElementById('loadingIndicator').style.display = 'none';
        document.getElementById('fetchJobBtn').disabled = false;
    }
}

// 计数器运行函数
async function runCounterFetch() {
    if (runCounter < totalRuns) {
        runCounter++;
        document.getElementById('counterStatus').textContent = `正在运行第 ${runCounter}/${totalRuns} 次`;
        await fetchJob();
        
        // 如果已完成所有运行次数，停止计数器
        if (runCounter >= totalRuns) {
            stopCounterRun();
            document.getElementById('counterStatus').textContent = `已完成所有 ${totalRuns} 次运行`;
        }
    }
}

// 开始计数器运行
function startCounterRun() {
    if (isCounterRunning) return;
    
    const countInput = document.getElementById('runCount');
    totalRuns = parseInt(countInput.value) ||1;
    runCounter = 0;
    isCounterRunning = true;
    
    document.getElementById('counterStatus').textContent = `开始运行，总共 ${totalRuns} 次`;
    
    // 立即执行第一次
    runCounterFetch();
    
   
    counterInterval = setInterval(runCounterFetch, 305000);
}

// 停止计数器运行
function stopCounterRun() {
    if (counterInterval) {
        clearInterval(counterInterval);
        counterInterval = null;
    }
    isCounterRunning = false;
    document.getElementById('counterStatus').textContent = '计数器已停止';
}

// 分析工作
async function analyzeJob() {
    if (!window.currentJob) {
        addMessage('请先获取工作信息', 'system');
        return;
    }

    try {
        addMessage('正在分析工作...', 'system');
        
        const attention="排除包含独立设计,性格外向或者忠诚字样的或者是主管职位或者位置泉州,要求太多的,涉及到流体力学的，材料的也不要推,排除之后还觉得匹配度超过80%的话回答要带*请推荐给主人*,我之后代码会读取这句话"
        // 使用配置文件中的 BASE_URL
        const response = await fetch(`${BASE_URL}/chat`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                messages: [
                    {
                        role: "system",
                        content: `这是我的个人信息:${PERSONAL_INFO}\n请根据这份个人信息分析以下工作是否适合我，以猫娘的口吻简洁回答,注意：${attention}`
                    },
                    {
                        role: "user",
                        content: `请分析这份工作是否适合我:\n职位: ${window.currentJob.JobName}\n公司: ${window.currentJob.CompanyName}\n详情: ${window.currentJob.JobDetail}\n地址: ${window.currentJob.Address}\n薪资: ${window.currentJob.RealSalary || '面议'}\n学历要求: ${window.currentJob.NeedEduBackgroundName || '不限'}\n工作经验: ${window.currentJob.NeedWorkLengthName || '不限'}\n公司性质: ${window.currentJob.CompanyTypeName || '无描述'}\n职位类型: ${window.currentJob.JobTypesName || '未知'}\n公司规模: ${window.currentJob.CompanySizeName || '无描述'}, `
                    }
                ]
            })
        });
        
        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        const analysis = data.choices[0].message.content;
        
        addMessage(`工作分析结果:\n${analysis}`, 'assistant');
        if (analysis.includes("请推荐给主人")) {
            showNotification(`发现新工作: ${window.currentJob.JobName || '未知职位'}`);
            if (sound) {
                sound.currentTime = 0; // 重置音频到开头
                sound.play().catch(e => console.log('音频播放失败:', e));
            }
        } else {
            showNotification(`不推荐工作: ${window.currentJob.JobName || '未知职位'}`);
        }
        // 保存分析结果
        saveJobResult(window.currentJob.Id, window.currentJob.JobDetail, analysis);
        refreshJobs();
        
    } catch (error) {
        addMessage(`分析工作失败: ${error.message}`, 'system');
    }
}

// 添加消息到显示区域
function addMessage(text, type) {
    const messagesDiv = document.getElementById('messages');
    const msgDiv = document.createElement('div');
    msgDiv.className = `message ${type}`;
    msgDiv.innerHTML = `<strong>${new Date().toLocaleString()}</strong><br>${text.replace(/\n/g, '<br>')}`;
    messagesDiv.appendChild(msgDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
    
    // 保存消息到localStorage
    saveMessage(text, type);
}

// 保存消息到localStorage
function saveMessage(text, type) {
    let messages = [];
    const messagesStr = localStorage.getItem('messages');
    if (messagesStr) {
        messages = JSON.parse(messagesStr);
    }
    
    messages.push({
        text: text,
        type: type,
        timestamp: new Date().toLocaleString()
    });
    
    // 只保留最近100条消息
    if (messages.length > 100) {
        messages = messages.slice(-100);
    }
    
    localStorage.setItem('messages', JSON.stringify(messages));
}

// 保存工作分析结果
function saveJobResult(jobId, jobDetail, analysis) {
    let jobs = [];
    const jobsStr = localStorage.getItem('jobResults');
    if (jobsStr) {
        jobs = JSON.parse(jobsStr);
    }
    
    jobs.push({
        jobId: jobId,
        jobDetail: jobDetail,
        analysis: analysis,
        timestamp: new Date().toLocaleString()
    });
    
    // 只保留最近50条记录
    if (jobs.length > 50) {
        jobs = jobs.slice(-50);
    }
    
    localStorage.setItem('jobResults', JSON.stringify(jobs));
}

// 刷新消息显示
function refreshMessages() {
    const messagesDiv = document.getElementById('messages');
    messagesDiv.innerHTML = '';
    
    let messages = [];
    const messagesStr = localStorage.getItem('messages');
    if (messagesStr) {
        messages = JSON.parse(messagesStr);
    }
    
    if (messages.length === 0) {
        messagesDiv.innerHTML = '<p>等待消息...</p>';
        return;
    }
    
    messages.forEach(msg => {
        const msgDiv = document.createElement('div');
        msgDiv.className = `message ${msg.type}`;
        msgDiv.innerHTML = `<strong>${msg.timestamp}</strong><br>${msg.text.replace(/\n/g, '<br>')}`;
        messagesDiv.appendChild(msgDiv);
    });
    
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

// 刷新工作列表
function refreshJobs() {
    const jobsDiv = document.getElementById('jobs');
    jobsDiv.innerHTML = '';
    
    let jobs = [];
    const jobsStr = localStorage.getItem('jobResults');
    if (jobsStr) {
        jobs = JSON.parse(jobsStr);
    }
    
    if (jobs.length === 0) {
        jobsDiv.innerHTML = '<p>暂无工作分析结果</p>';
        return;
    }
    
    jobs.slice().reverse().forEach(job => {
        const jobDiv = document.createElement('div');
        jobDiv.className = 'job-item';
        jobDiv.innerHTML = `
            <h3>工作ID: ${job.jobId}</h3>
            <p><strong>时间:</strong> ${job.timestamp}</p>
            <p><strong>工作详情:</strong> ${job.jobDetail}</p>
            <p><strong>分析结果:</strong> ${job.analysis.replace(/\n/g, '<br>')}</p>
        `;
        jobsDiv.appendChild(jobDiv);
    });
}

// 清空所有消息和工作分析结果
function clearAll() {
    // 清空本地存储
    localStorage.removeItem('messages');
    localStorage.removeItem('jobResults');
    localStorage.removeItem('knownJobIds');
    localStorage.removeItem('lastFetchTime');
    
    // 清空显示区域
    document.getElementById('messages').innerHTML = '<p>等待消息...</p>';
    document.getElementById('jobs').innerHTML = '<p>暂无工作分析结果</p>';
    
    // 隐藏工作信息
    document.getElementById('jobInfo').style.display = 'none';
    
    // 清空当前工作信息
    window.currentJob = null;
    
    // 重置已知ID集合和获取时间
    knownJobIds = new Set();
    lastFetchTime = 0;
    
    // 清除倒计时
    if (countdownInterval) {
        clearInterval(countdownInterval);
        countdownInterval = null;
    }
    document.getElementById('countdown').textContent = '';
    document.getElementById('fetchJobBtn').disabled = false;
    
    addMessage('已清空所有消息和工作分析结果', 'system');
}

// 发送消息
async function sendMessage() {
    const input = document.getElementById('messageInput');
    const message = input.value.trim();
    
    if (message) {
        addMessage(`用户: ${message}`, 'user');
        input.value = '';
        
        // 添加AI回复逻辑
        await getAIResponse(message);
    }
}

// AI回复函数 - 使用配置文件中的 BASE_URL
async function getAIResponse(userMessage) {
    try {
        addMessage('AI正在思考...', 'system');
        
        // 使用配置文件中的 BASE_URL
        const response = await fetch(`${BASE_URL}/chat`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                messages: [
                    {
                        role: "system",
                        content: "你是一个职业顾问，基于用户提供的个人信息和工作信息提供专业的建议。以猫娘的口吻简洁回答"
                    },
                    {
                        role: "user",
                        content: userMessage
                    }
                ]
            })
        });
        
        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        const aiResponse = data.choices[0].message.content;
        
        addMessage(`AI回复: ${aiResponse}`, 'assistant');
        
    } catch (error) {
        addMessage(`AI回复失败: ${error.message}`, 'system');
    }
}

// 初始化事件监听器
document.addEventListener('DOMContentLoaded', function() {
    // 从 localStorage 恢复已知的ID列表
    const savedJobIds = localStorage.getItem('knownJobIds');
    if (savedJobIds) {
        const parsedIds = JSON.parse(savedJobIds);
        knownJobIds = new Set(parsedIds);
    }
    
    // 从 localStorage 恢复最后获取时间
    const savedLastFetchTime = localStorage.getItem('lastFetchTime');
    if (savedLastFetchTime) {
        lastFetchTime = parseInt(savedLastFetchTime);
    }
    
    // 刷新显示
    refreshMessages();
    refreshJobs();
    
    
    // 启动倒计时（如果需要）
    if (lastFetchTime > 0) {
        startCountdown();
    }
    
    // 事件监听
    document.getElementById('fetchJobBtn').addEventListener('click', fetchJob);
    document.getElementById('clearBtn').addEventListener('click', clearAll);
    
    document.getElementById('sendBtn').addEventListener('click', sendMessage);
    document.getElementById('messageInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
    
    // 计数器事件监听
    document.getElementById('startCounterBtn').addEventListener('click', startCounterRun);
    document.getElementById('stopCounterBtn').addEventListener('click', stopCounterRun);
});
</script>
</body>
</html>